<?php

namespace app\admin\controller\insurance;

use app\admin\model\InsuranceImport;
use app\admin\model\InsurancePolicy;
use app\admin\service\TriggerService;
use app\common\constants\MenuConstant;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;
use app\common\controller\AdminController;
use app\Request;
use think\App;
use think\response\Json;

#[ControllerAnnotation(title: '代理人')]
class Import extends AdminController
{
    protected array $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        self::$model = InsuranceImport::class;
    }

    #[NodeAnnotation(title: '列表', auth: true)]
    public function index(Request $request): Json|string
    {
        if ($request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            $count = self::$model::where($where)->count() ?: 0;
            $list  = self::$model::where($where)->order($this->sort)->page($page, $limit)->select()->toArray() ?: [];
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    

    #[NodeAnnotation(title: '导入', auth: true)]
    public function import(Request $request): Json|string{
        if ($request->post()){
            $data = $request->post();
    
            $ident = date('YmdHis').rand(1000,9999);
            $validData = [];
            foreach ($data as $index => $row) {
                $d = [
                    'create_at' => str_replace('/', '-', $row['col1']),
                    'start_at' => str_replace('/', '-', $row['col2']),
                    'end_at' => str_replace('/', '-', $row['col3']),
                    'carno' => $row['col4'],
                    'insurer' => $row['col5'],
                    'is_chesun' => $row['col6'] == '是' ? 1 : 0,
                    'cost_sy' => $row['col7'],
                    'cost_jq' => $row['col8'],
                    'cost_cc' => $row['col9'],
                    'cost_jc' => $row['col10'],
                    'agent' => $row['col11'],
                    'ident' => $ident,
                    'status' => $row['status']
                ];
                $record = self::$model::where(['create_at' => strtotime($d['create_at']), 'carno' => $d['carno'], 'insurer' => $d['insurer']])->find();
                if ($record) {
                    $d['status'] = 0;
                }
                $validData[] = $d;
            }
            // return json($validData);
            // 批量写入数据库（使用模型的批量插入）
            if (!empty($validData)) {
                $model = new self::$model(); // 替换为实际模型
                $model->saveAll($validData);
                $this->success('导入成功，共导入 ' . count($validData) . ' 条数据');
            } else {
                $this->error('无有效数据可导入');
            }

        }

        return $this->fetch();
    }

    #[NodeAnnotation(title: '转移数据', auth: true)]
    public function transfer(Request $request): Json{
        if ($request->post()){
            $data = $request->post();
            $ids = $data['id'];
            if (empty($ids)){
                $this->error('请选择要转移的数据');
            }
            $fields = ['create_at', 'start_at', 'end_at', 'carno', 'insurer', 'is_chesun', 'cost_sy', 'cost_jq', 'cost_cc', 'cost_jc', 'agent', 'idcard'];
            $list = self::$model::whereIn('id', $ids)->where('status', 1)->field($fields)->select()->toArray();
            if (empty($list)){
                $this->error('无数据可转移');
            }
            $this->error('转移失败', $list);
            $model = new InsurancePolicy();
            foreach ($list as $item){
                $model->save($item);
            }
            $this->success('转移成功');
        }
        $this->error('error');
    }
}
